package com.archer.security.service.impl;

import com.archer.data.access.AppUserAccess;
import com.archer.data.model.AppUser;
import com.archer.security.service.SecurityUserService;
import com.archer.security.model.SecurityRole;
import com.archer.security.model.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * Created by luohuida-2895 on 2015/5/1.
 */
public class SecurityUserServiceImpl implements SecurityUserService {
    @Autowired
    private AppUserAccess appUserAccess;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        AppUser appUser = appUserAccess.getByUserName(username);
        if (appUser == null) {
            return null;
        }

        SecurityUser securityUser = new SecurityUser();
        securityUser.setUsername(username);
        securityUser.setPassword(appUser.getPassword());

        SecurityRole role = new SecurityRole("default", "正常用户都有的权限");

        securityUser.getAuthorities().add(role);
        String group = appUser.getGroup();
        if (group != null && group.length() > 0) {
            String[] groupArr = group.split(",");
            for (String s : groupArr) {
                role = new SecurityRole(s, "");
                securityUser.getAuthorities().add(role);
            }
        }
        return securityUser;
    }
}
